import utils from '../../utils/util.js'
import api from "../../api/report.js";
import openFileFunc from '../../utils/openFileFunc.js'
var now = new Date();
var month = now.getMonth();
var year = now.getFullYear();
var keyTime = 'beginDate'
const app = getApp();
const apiUrl = app.globalData.apiUrl;


Page({
  data: {
    beginDate: utils.formatTime(new Date(year, month, 1)),
    endDate: utils.formatTime(new Date(year, month + 1, 1)),
    currentDate: new Date(utils.formatTime(new Date(year, month, 1))).getTime(),
    minDate: new Date('2023/12').getTime(),
    showSheet: false,
    list: []
  },
  onLoad(options) {
    const item = JSON.parse(options.item)
    this.setData({
      beginDate: item.beginDate,
      endDate: item.endDate
    }, () => {
      this.onInitData()
    })
  },
  async onInitData() {
    const res = await api.monthReportDetail({
      beginDate: this.data.beginDate?.trim(),
      endDate: this.data.endDate?.trim(),
    })
    if (res.data?.length) {
      this.setData({
        list: res.data.filter(ele => ele.breedName),
        totalSum: res.data.find(ele => !ele.breedName && ele.countSum?.includes('合计'))?.totalSum,
        countSum: res.data.find(ele => !ele.breedName && ele.totalSum?.includes('合计'))?.countSum
      })
    } else {
      this.setData({
        list: [],
        totalSum: '',
        countSum: '',
      })
    }
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail
    });
  },
  onShowTimer(e) {
    keyTime = e.currentTarget.dataset.type
    this.setData({
      showSheet: true,
      currentDate: new Date(this.data[keyTime]).getTime()
    });
  },
  onClose() {
    this.setData({
      showSheet: false,
      [keyTime]: utils.formatTime(new Date(this.data.currentDate)),
    }, () => {
      this.onInitData()
    });
  },
  exportMonth() {
    const beginDate = this.data.beginDate?.trim()
    const endDate = this.data.endDate?.trim()
    api.exportMonth({
      beginDate: beginDate,
      endDate: endDate,
    }).then(res => {
      openFileFunc(res, `${beginDate.replaceAll('-','_')}_${endDate.replaceAll('-','_')}`)
    })
  }
})